package pzl.com.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import pzl.com.bluetooth.adapter.ReceiveDataAdapter;
import pzl.com.bluetooth.bean.BluetoothMessage;
import pzl.com.bluetooth.constant.ConstantUtils;
import pzl.com.bluetooth.utils.BitmapUtil;
import pzl.com.bluetooth.utils.BluetoothUtils;


public class SendActivity extends BaseActivity {
    public static final String TAG = "SendActivity";

    private ListView lvData;
    private EditText et;
    private ImageView ivPreview;
    private RelativeLayout rl;
    private Button btnSendText;

    private ReceiveDataAdapter receiveDataAdapter;

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothUtils bluetoothUtils;
    private String clientAddress;
    private String serviceAddress;
    private String remoteAddress;

    private Bitmap selectedPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        registerBroadcastReceiver(new String[]{ConstantUtils.ACTION_RECEIVER_BLUETOOTHMESSAGE,
                ConstantUtils.ACTION_RECEIVER_SERVERACCEPT});
        initData();
        initView();
    }

    private void initData() {
        clientAddress = getIntent().getStringExtra("clientAddress");
        serviceAddress = getIntent().getStringExtra("serviceAddress");
        remoteAddress = clientAddress == null ? serviceAddress : clientAddress;

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothUtils = BluetoothUtils.getInstance();

        /**
         * connect()是一个阻塞调用;
         * 执行这个调用时，系统将会在远程设备上执行一个SDP查找工作，来匹配UUID。如果查找成功，并且远程设备接受了连接，它将会在连接过程中分享RFCOMM通道，而 connect() 将会返回。这个方法是阻塞的。如果，处于任何原因，该连接失败了或者connect()超时了（大约12秒以后），那么它将会抛出一个异常。
         */
        /**
         * 确保在你调用connect()时设备没有执行设备查找工作。如果正在查找设备，那么连接尝试将会很大程度的减缓，并且很有可能会失败。
         */
        receiveDataAdapter = new ReceiveDataAdapter(this);
    }

    private void initView() {
        et = (EditText) findViewById(R.id.et);
        lvData = (ListView) findViewById(R.id.lvData);
        ivPreview = (ImageView) findViewById(R.id.ivPreview);
        rl = (RelativeLayout) findViewById(R.id.rl);
        btnSendText = (Button) findViewById(R.id.btnSendText);

        lvData.setAdapter(receiveDataAdapter);
        setTitle(bluetoothUtils.mBluetoothAdapter.getAddress());
    }

    public void click(View v) {
        switch (v.getId()) {
            case R.id.btnSendText:
                if (selectedPic == null) {
                    String send = et.getText().toString().trim();
                    BluetoothMessage message = new BluetoothMessage();
                    message.message = send;
                    message.type = BluetoothMessage.TYPE_TEXT;
                    if (clientAddress == null) {//当前设备是客服端
                        message.receiver = serviceAddress;
                        message.sender = bluetoothAdapter.getAddress();
                    } else {//当前设备是服务端
                        message.receiver = clientAddress;
                        message.sender = bluetoothAdapter.getAddress();
                    }

                    Map<String, Object> item = new HashMap();
                    item.put("text", send);
                    item.put("nick", bluetoothAdapter.getName());
                    item.put("identity", 0);
                    receiveDataAdapter.addItem(item);
                    receiveDataAdapter.notifyDataSetChanged();
                    lvData.smoothScrollBy(Integer.MAX_VALUE, 500);//smooth Long.MAX_VALUE

                    bluetoothUtils.sendBluetoothMessageToRemote(message, remoteAddress);
                    et.setText("");
                } else {
                    btnSendText.setEnabled(false);
                    BluetoothMessage message = new BluetoothMessage();
                    message.message = BitmapUtil.getBytes(selectedPic);
                    message.type = BluetoothMessage.TYPE_BITMAP;
                    if (clientAddress == null) {//当前设备是客服端
                        message.receiver = serviceAddress;
                        message.sender = bluetoothAdapter.getAddress();
                    } else {//当前设备是服务端
                        message.receiver = clientAddress;
                        message.sender = bluetoothAdapter.getAddress();
                    }
                    Map<String, Object> item = new HashMap();
                    item.put("img", selectedPic);
                    item.put("nick", bluetoothAdapter.getName());
                    item.put("identity", 0);
                    receiveDataAdapter.addItem(item);
                    receiveDataAdapter.notifyDataSetChanged();
                    lvData.smoothScrollBy(Integer.MAX_VALUE, 500);//smooth Long.MAX_VALUE

                    bluetoothUtils.sendBluetoothMessageToRemote(message, remoteAddress);
                    rl.setVisibility(View.VISIBLE);
                    ivPreview.setVisibility(View.GONE);
                    selectedPic = null;
                    btnSendText.setEnabled(true);
                }
                break;
            case R.id.ivOpenImg:
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    protected void onReceiveBluetoothMessage(BluetoothMessage bluetoothMessage) {
        super.onReceiveBluetoothMessage(bluetoothMessage);
        Log.d(TAG, "onReceive蓝牙消息= " + bluetoothMessage.toString());

        String nick = bluetoothAdapter.getRemoteDevice(bluetoothMessage.sender).getName();
        Map<String, Object> item = new HashMap();
        item.put("nick", nick);
        item.put("identity", 1);

        switch (bluetoothMessage.type) {
            case BluetoothMessage.TYPE_TEXT:
                String text = (String) bluetoothMessage.message;
                item.put("text", text);
                receiveDataAdapter.addItem(item);
                receiveDataAdapter.notifyDataSetChanged();
                lvData.smoothScrollBy(Integer.MAX_VALUE, 500);//smooth Long.MAX_VALUE
                break;
            case BluetoothMessage.TYPE_BITMAP:
                Bitmap bitmap = BitmapUtil.getBitmap((byte[]) bluetoothMessage.message);
                item.put("img", bitmap);
                receiveDataAdapter.addItem(item);
                receiveDataAdapter.notifyDataSetChanged();
                lvData.smoothScrollBy(Integer.MAX_VALUE, 500);//smooth Long.MAX_VALUE
                break;
        }
    }

    @Override
    protected void onAcceptedNew(String clientAddress) {
        this.clientAddress = clientAddress;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        rl.setVisibility(View.GONE);
        ivPreview.setVisibility(View.VISIBLE);
        Uri uri = data.getData();
        ContentResolver cr = this.getContentResolver();
        try {
            selectedPic = BitmapFactory.decodeStream(cr.openInputStream(uri));
            ivPreview.setImageBitmap(selectedPic);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
